# -*- coding: utf-8 -*-

'''
用户相关函数
'''
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess
import pandas as pd
import uuid
import datetime
import re
import hashlib
from ...pao_python.pao.service.security.security_service import RoleService
from ...pao_python.pao.service.security.security_utility import get_current_account_id


class UserServer(DataProcess):

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.RoleService = RoleService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_user_list(self, condition, page, count):
        condition_account = {}
        if 'role_ids' in condition.keys():
            condition_account['role_ids'] = condition['role_ids']
        else:
            role_res = self.RoleService.get_role_list({}, 1, 999)
            role_ids = []
            for obj in role_res['result']:
                role_ids.append(obj['id'])
            condition_account['role_ids'] = role_ids
        if 'account' in condition.keys():
            condition_account['account'] = condition['account']
        else:
            condition_account['account'] = ''
        user_name = ''
        if 'user_name' in condition.keys():
            user_name = condition['user_name']

        role_res = self.RoleService.get_account_role_list(
            condition_account, page, count)
        if role_res == '无查询结果':
            return {'total': 0, 'result': []}
        else:
            role_df = pd.DataFrame(role_res['result'])
            account_ids = role_df['account_id'].tolist()
            user_df = ''

            def process_func(db):
                nonlocal user_df
                collection_user = db['PT_User']
                if len(user_name) > 0:
                    user_cur = collection_user.find(
                        {'account_id': {'$in': account_ids}, 'name': re.compile(user_name)})
                else:
                    user_cur = collection_user.find(
                        {'account_id': {'$in': account_ids}})
                user_df = pd.DataFrame(list(user_cur[:]))
                user_df = user_df.rename(columns={'id': 'user_id'})
                if len(user_df) > 0:
                    user_df = user_df[['name', 'user_id',
                                       'comment', 'create_date', 'account_id']]
            process_db(self.db_addr, self.db_port, self.db_name,
                       process_func, self.db_user, self.db_pwd)
            if len(user_df) > 0:
                res_df = pd.merge(role_df, user_df,
                                  on='account_id', how='inner')
                res_df['create_date'] = res_df['create_date'].map(
                    lambda x: x.strftime('%Y-%m-%d'))
                res = {'total': role_res['total'],
                       'result': dataframe_to_list(res_df)}
            else:
                res = {'total': 0, 'result': []}
            return res

    def get_current_user(self):
        account_id = get_current_account_id(self.session)
        user_df = ''

        def process_func(db):
            nonlocal user_df
            collection_user = db['PT_User']
            print(account_id, 'account_id')
            user_cur = collection_user.find({'account_id': account_id})
            user_df = pd.DataFrame(list(user_cur[:]))
            user_df = user_df.drop(["_id"], axis=1)
            user_df = user_df.drop(["id"], axis=1)
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        acc_df = pd.DataFrame(self.RoleService.get_current_account())
        res_df = pd.merge(user_df, acc_df, left_on='account_id',
                          right_on='id', how='inner')
        if 'email' not in res_df.columns:
            res_df['email'] = ''
        res_list = dataframe_to_list(res_df)
        return res_list

    def get_user_by_id(self, user_id):
        user_df = ''
        account_id = ''

        def process_func(db):
            nonlocal user_df, account_id
            collection_user = db['PT_User']
            user_cur = collection_user.find({'id': user_id})
            user_df = pd.DataFrame(list(user_cur[:]))
            account_id = user_df['account_id'].iloc[0]
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        res_list = self.RoleService.get_account_by_id(account_id)
        res_list['name'] = user_df['name'].iloc[0]
        res_list['comment'] = user_df['comment'].iloc[0]
        res_list['id'] = user_df['id'].iloc[0]
        return res_list

    def update_user(self, User):
        '''
        User包含的关键字:id, name,comment,account,role_id
        '''
        account_id = ''

        def process_func_find(db):
            nonlocal account_id
            if 'id' in User.keys() and len(User['id']) > 0:
                collection_user = db['PT_User']
                user_cur = collection_user.find({'id': User['id']})
                user_df = pd.DataFrame(list(user_cur[:]))
                account_id = user_df['account_id'].iloc[0]
            else:
                account_id = ''
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func_find, self.db_user, self.db_pwd)

        Data = {'account_id': account_id,
                'account': User['account'], 'role_id_list': User['role_id']}
        res_acc = self.RoleService.update_account_role(Data)

        if res_acc == 'Success':
            def process_func(db):

                if 'id' in User.keys() and len(User['id']) > 0:
                    collection_user = db['PT_User']
                    collection_user.update({'id': User['id']}, {
                                           '$set': {'name': User['name'], 'comment': User['comment']}})
                else:
                    collection_account = db['PT_Account']
                    acc_cur = collection_account.find(
                        {'account': User['account']})
                    acc_df = pd.DataFrame(list(acc_cur[:]))
                    account_id = acc_df['id'].iloc[0]
                    date = datetime.datetime.now()
                    user_data = {'id': str(uuid.uuid1()), 'name': User['name'],
                                 'comment': User['comment'],
                                 'account_id': account_id,
                                 'caict_account': User['caict_account'],
                                 'caict_pw': User['caict_pw'],
                                 'create_date': date}
                    collection_user = db['PT_User']
                    collection_user.insert(user_data)
            process_db(self.db_addr, self.db_port, self.db_name,
                       process_func, self.db_user, self.db_pwd)
            return 'Success'
        else:
            return res_acc

    def delete_user(self, user_id_list):
        account_ids = ''

        def process_func(db):
            nonlocal account_ids
            collection_user = db['PT_User']
            user_cur = collection_user.find({'id': {'$in': user_id_list}})
            user_df = pd.DataFrame(list(user_cur[:]))
            account_ids = user_df['account_id'].tolist()
            collection_user.remove({'id': {'$in': user_id_list}})
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        res = self.RoleService.del_account(account_ids)
        return res

    def reset_password(self, user_id):
        account_id = ''

        def process_func(db):
            nonlocal account_id
            collection_user = db['PT_User']
            user_cur = collection_user.find({'id': user_id})
            user_df = pd.DataFrame(list(user_cur[:]))
            account_id = user_df['account_id'].iloc[0]
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        res = self.RoleService.reset_password(account_id)
        return res

    '''通过账户获取用户id'''

    def get_user_by_acount(self, account):
        user_info = []

        def process_func(db):
            nonlocal user_info
            col_acount = db['PT_Account']
            col_user = db['PT_User']
            print('this1')
            account_info = list(col_acount.find({'account': account}))
            print(account_info, 'account_info')
            if len(account_info) > 0:
                user_info = list(col_user.find(
                    {'account_id': account_info[0]['id']}))
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return user_info

    def get_current_user_by_account_id(self, account_id):
        '''获取当前用户信息'''
        user_df = ''
        acc_df = ''

        def process_func(db):
            nonlocal user_df, acc_df
            collection_user = db['PT_User']
            user_cur = collection_user.find({'account_id': account_id})
            user_df = pd.DataFrame(list(user_cur[:]))
            user_df = user_df.drop(["_id"], axis=1)
            user_df = dataframe_to_list(user_df)
            # collection_account=db['PT_Account']
            # acc_cur=collection_account.find({'id':account_id})
            # acc_df=pd.DataFrame(list(acc_cur[:]))
            # acc_df=acc_df.drop(["_id"], axis=1)
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        # res_df=pd.merge(user_df,acc_df,left_on='account_id',right_on='id',how='inner')
        # if 'email'  not in  res_df.columns:
        #     res_df['email']=''
        # res_list=dataframe_to_list(res_df)
        return user_df[0]
